package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import domian.Chat;
import domian.Message;
import domian.User;
import redis.clients.jedis.Jedis;
import service.ChatService;
import service.MessageService;
import service.UserService;
import service.impl.ChatServiceImpl;
import service.impl.MessageServiceImpl;
import service.impl.UserServiceImpl;
import utils.Redis;
import utils.ToolSet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@WebServlet("/chat/*")
public class ChatServlet extends BaseServlet{
    MessageService messageService = new MessageServiceImpl();
    ChatService chatService = new ChatServiceImpl();
    UserService userService = new UserServiceImpl();

    /**
     * 初始化数据
     * @param req
     * @param resp
     * @throws IOException
     */
    public void init(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String fid = req.getParameter("fid");
        System.out.println("fid :"+fid);
        //取出User
        Jedis jedis = new Jedis();
        //获取用户客户端标识
        String redisKey = Redis.getRedisKey(req);
        String s = jedis.get(redisKey);
        ObjectMapper objectMapper = new ObjectMapper();
        User user = objectMapper.readValue(s, User.class);
        resp.setHeader("Refresh", "10;url=/chat.html");

        //所有消息
        Map<String, List<String>> allMessageById = messageService.findAllMessageById(user.getUid());
        //登录本人
        List<String> my=  new ArrayList<>();
        my.add(user.getNickname()+"?"+"http://192.168.17.12:8060/"+user.getHeaderimg()+"?"+user.getUid());
        allMessageById.put("myUser",my);

        //聊天好友
        List<String> F_list = allMessageById.get("friend");
        //聊天好友用户id
        String[] split1 = F_list.get(0).split("-");
        //好友集合
        List<String> FriendList = new ArrayList<>();
        for (String s1 : split1) {
            User userById = userService.findUserById(Integer.parseInt(s1));
            FriendList.add(userById.getNickname()+"?"+"http://192.168.17.12:8060/"+userById.getHeaderimg()+"?"+userById.getUid());
        }
        allMessageById.put("friendData",FriendList);

        //黑名单
        List<String> B_list = allMessageById.get("black");
        //黑名单用户id
        String[] split = B_list.get(0).split("-");
        //黑名单集合
        List<String> userData = new ArrayList<>();
        for (String s1 : split) {
            User userById = userService.findUserById(Integer.parseInt(s1));
            userData.add(userById.getNickname()+"?"+"http://192.168.17.12:8060/"+userById.getHeaderimg()+"?"+userById.getUid());
        }
        allMessageById.put("userData",userData);


        //记录 各种消息的数量
        List<String> O_list = allMessageById.get("offical");
        List<String> I_list = allMessageById.get("infrom");

        //官方消息数量
        int o_size = O_list.size();
        //通知消息数量
        int i_size = I_list.size();
        //私信数量
        int c_size = chatService.findChatSum(user.getUid());
        //将数量拼接到信息中
        String size = o_size+"-"+i_size+"-"+c_size;
        List<String> sizelist = new ArrayList<>();
        sizelist.add(size);
        allMessageById.put("sum",sizelist);
        ToolSet.printWriter(resp,allMessageById);
    }

    /**
     * 更新消息通知
     * @param req
     * @param resp
     */
    public void updateMessage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //取出User
        Jedis jedis = new Jedis();
        //获取用户客户端标识
        String redisKey = Redis.getRedisKey(req);
        String s = jedis.get(redisKey);
        ObjectMapper objectMapper = new ObjectMapper();
        User user = objectMapper.readValue(s, User.class);
        //所有消息
        Map<String, List<String>> allMessageById = messageService.findAllMessageById(user.getUid());
        //记录 各种消息的数量
        List<String> O_list = allMessageById.get("offical");
        List<String> I_list = allMessageById.get("infrom");
        //官方消息数量
        int o_size = O_list.size();
        //通知消息数量
        int i_size = I_list.size();
        //私信数量
        int c_size = chatService.findChatSum(user.getUid());
        //将数量拼接到信息中
        String size = o_size+"-"+i_size+"-"+c_size;
        List<String> sizelist = new ArrayList<>();
        sizelist.add(size);
        allMessageById.put("sum",sizelist);
        ToolSet.printWriter(resp,allMessageById);
    }


    /**
     * 更新聊天通知
     * @param req
     * @param resp
     * @throws IOException
     */
    public void  chatRecord(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String sendId = req.getParameter("id");
        //获取发送者信息
        User userById = userService.findUserById(Integer.parseInt(sendId));
        Jedis jedis = new Jedis();
        //获取用户客户端标识
        String redisKey = Redis.getRedisKey(req);
        String s = jedis.get(redisKey);
        ObjectMapper objectMapper = new ObjectMapper();
        User user = objectMapper.readValue(s, User.class);
        Integer uid = user.getUid();
        Map<String, List<String>> allChatBySendUserIdAndReceiptUser = chatService.findAllChatBySendUserIdAndReceiptUser(Integer.parseInt(sendId), uid);

        List<String> S_img = new ArrayList<>();
        List<String> R_img = new ArrayList<>();
        S_img.add("http://192.168.17.12:8060/"+userById.getHeaderimg());
        R_img.add("http://192.168.17.12:8060/"+user.getHeaderimg());
        allChatBySendUserIdAndReceiptUser.put("sendImg",S_img);
        allChatBySendUserIdAndReceiptUser.put("receiptImg",R_img);
        ToolSet.printWriter(resp,allChatBySendUserIdAndReceiptUser);
    }
    public void updateChat(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Jedis jedis = new Jedis();
        //获取用户客户端标识
        String redisKey = Redis.getRedisKey(req);
        String s = jedis.get(redisKey);
        ObjectMapper objectMapper = new ObjectMapper();
        User user = objectMapper.readValue(s, User.class);
        Integer sendUid = user.getUid();
        String receptId = req.getParameter("recept");
        String content = req.getParameter("content");
        String time = req.getParameter("time");
        Chat chat = new Chat(sendUid, Integer.parseInt(receptId), content, time);
        chatService.addChat(chat);
    }
    /**
     * 加入黑名单
     */
    public  void  addBlack(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String blickId = req.getParameter("blickId");
        System.out.println("黑名单id:"+blickId);
        Jedis jedis = new Jedis();
        //获取用户客户端标识
        String redisKey = Redis.getRedisKey(req);
        String s = jedis.get(redisKey);
        ObjectMapper objectMapper = new ObjectMapper();
        User user = objectMapper.readValue(s, User.class);
        Integer Uid = user.getUid();
        Message messageById = messageService.findMessageById(Uid);
        String blacklist = messageById.getBlacklist();
        if (blacklist!=null){
            messageById.setBlacklist(blacklist+"-"+blickId);
            String friend_id = messageById.getFriend_id();

            String[] split = friend_id.split("-");
            String friend_newId ="";
            for (String s1 : split) {
                if (!s1.equals(blickId)){
                       friend_newId+="-"+s1;
                }
            }
            friend_newId = friend_newId.substring(1);
            messageById.setFriend_id(friend_newId);
            System.out.println(friend_newId);

        }
        messageService.updateMessage(messageById);
    }
    /**
     * 解除黑名单
     */
    public  void  removeBlack(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String blickId = req.getParameter("backId");
        System.out.println("黑名单id:"+blickId);
        Jedis jedis = new Jedis();
        //获取用户客户端标识
        String redisKey = Redis.getRedisKey(req);
        String s = jedis.get(redisKey);
        ObjectMapper objectMapper = new ObjectMapper();
        User user = objectMapper.readValue(s, User.class);
        Integer Uid = user.getUid();

        Message messageById = messageService.findMessageById(Uid);
        //获取朋友列表
        String friendList = messageById.getFriend_id();
        //
        if (friendList!=null){
            //将拉黑的人加入朋友列表
            messageById.setFriend_id(friendList+"-"+blickId);

            String friend_id = messageById.getBlacklist();

            String[] split = friend_id.split("-");
            String friend_newId ="";
            for (String s1 : split) {
                if (!s1.equals(blickId)){
                    friend_newId+="-"+s1;
                }
            }
            friend_newId = friend_newId.substring(1);


            messageById.setBlacklist(friend_newId);
            System.out.println(friend_newId);

        }
        messageService.updateMessage(messageById);
    }

}
